package com.common.config;

import com.alibaba.fastjson.JSONObject;
import com.common.constant.CommonConstant;
import com.common.util.CommonUtil;
import com.common.util.XsslHttpServletRequestWrapper;
import com.common.vo.LoginUser;
import com.common.vo.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.Set;


/**
 * 过滤配置器
 * @author YYQ
 *
 */
@WebFilter(urlPatterns = "/*",filterName = "myFilterConfig")
public class MyFilterConfig implements Filter{
	
	private final Logger logger = LoggerFactory.getLogger(MyFilterConfig.class);
	/** 编码格式*/
	public String encoding = "UTF-8";
	/** 不拦截的路径*/
	private final String [] notUrl = {
			"/guest",
			"/captcha",
			"/data",
			"/webSocket",
			"/api-docs",
			"/swagger",
			"/api",
			"/codeCheck",
			"/codeJudge",
			"/views/app"
	};


	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		// 请求头
		HttpServletRequest request = (HttpServletRequest)req;
		// 响应头
		HttpServletResponse response = (HttpServletResponse)res;
		// 编码设置
		response.setCharacterEncoding(encoding);
		response.setCharacterEncoding(encoding);
		response.setHeader("Content-type", "textml;charset=UTF-8");
		response.setContentType("text/html;charset="+encoding);
		// 防止XSS漏洞
		XsslHttpServletRequestWrapper xssRequest = new XsslHttpServletRequestWrapper(request);
		// 获取会话
		HttpSession session = request.getSession();
		String url = request.getRequestURI();
		// 不过滤的请求
		if(existsUrl(url) != -1) {
			chain.doFilter(xssRequest,response);
			return;
		}
		String s [] = url.split("/"); 
		if(s.length > CommonConstant.ZERO && s[s.length-1].indexOf(".") == -1) {
			if(s != null && s.length > CommonConstant.ZERO){
				logger.info("正在过滤路径："+request.getServletPath());
				LoginUser user =(LoginUser) session.getAttribute(CommonConstant.LOGIN_USER);
				if(user != null){
					// 锁屏情况下，其他请求提示未登录
					String suoPing = (String) session.getAttribute("suoPing");
					if(!s[s.length-1].equals("suoping")
							&& suoPing != null
							&& !suoPing.equals("ok")
							&& getParam(request) != -1){
						PrintWriter writer = response.getWriter();
						writer.write(Result.notLogin().toString());
						return;
					}
					// 这些请求直接跳主页
					final String projectName = request.getContextPath();
					if(s[s.length-1].equals("login") || ("/"+s[s.length-1]).equals(projectName)){// 登录成功过直接跳回主界面
						request.getRequestDispatcher("/jumpMain").forward(request, response);
						return ;
					}
					chain.doFilter(xssRequest,response);//交给下个过滤器
					return;
				}else{
					// 未登录放行
					if((s[s.length-1].equals("loginJudge") && request.getParameter("userName") != null)){// 登录校验请求
						chain.doFilter(xssRequest,response);
						return;
					}else if(url.indexOf("login") == -1 && url.indexOf("main") == -1 && getParam(request) != -1){
						PrintWriter writer = response.getWriter();
						writer.write(JSONObject.toJSONString(Result.notLogin().toString()));
						return;
					}
				}
			}
		}else {
			chain.doFilter(xssRequest,response);
			return;
		}
		request.getRequestDispatcher("/login").forward(request, response);// 直接跳转登录界面
	}

	/**
	 * 判断是否路径放行
	 * @param url
	 * @return
	 */
	public int existsUrl(String url){
		for (String s : notUrl) {
			if(url.indexOf(s) != -1){
				return 1;
			}
		}
		return -1;
	}

	/**
	 * 判断是否有参数，有则校验是否登录
	 * @param request
	 * @return
	 */
	public int getParam(HttpServletRequest request) {
		Map<String, String[]> map = request.getParameterMap();
		Set<Map.Entry<String, String[]>> keSet = map.entrySet();
		if(keSet.size() > CommonConstant.ZERO){
			return 1;
		}
		return -1;
	}

	@Override
	public void init(FilterConfig arg0){
		logger.info("初始化过滤器");
	}

	@Override
	public void destroy() {
		logger.info("销毁过滤器");
	}

	
}
